#include "Serveur.h"
#include <string>
#include <winsock2.h>
#include <stdio.h>
#include <iostream>
#include <iomanip>
#include <conio.h>

using namespace std;

Serveur::Serveur() : moduleSon(false)
{
    //ctor
}

Serveur::~Serveur()
{
    //dtor
}

int Serveur::connexion() {
    WSAStartup(MAKEWORD(2,0), &WSAData);
    sock = socket(AF_INET, SOCK_STREAM, 0);
    sin.sin_addr.s_addr = INADDR_ANY;
    sin.sin_family = AF_INET;
    sin.sin_port = htons(4444);
    bind(sock, (SOCKADDR *)&sin, sizeof(sin));
    listen(sock, 0);
    int sinsize = sizeof(csin);
    cout << "En attente de connexion" << endl;
    sockCHL = accept(sock, (SOCKADDR *)&csin, &sinsize);
    sockSon = accept(sock, (SOCKADDR *)&csin, &sinsize);
    cout << "Connexion acceptee" << endl;
    return 0;
}

bool Serveur::gestionTexte(){
    bool rester = true;
    FD_ZERO(&rfds);
    FD_SET(sockCHL, &rfds);
    tv.tv_sec = 0;
    tv.tv_usec = 0;
    retval = select(sockCHL+1, &rfds, NULL, NULL, &tv);
    if(retval==-1){
        rester = false;
    }

    if(kbhit()){
        envoyerTexte();
    }

    if(FD_ISSET(sockCHL,&rfds)){
        recevoirTexte();
    }
    return rester;
}
int Serveur::envoyerTexte(){
    char msg[256];
    cin.getline(msg,256);
    return send(sockCHL,msg,sizeof(msg),0);
}

int Serveur::recevoirTexte(){
    int sortie;
    char msg[256];
    sortie = recv(sockCHL,msg,sizeof(msg),0);
    if(sortie != -1){
        cout<<"Client dit : "<<msg<<endl;
    }
    return sortie;
}

void Serveur::activerSon(){
    moduleSon = true;
}

bool Serveur::sonDisponible(){
    return false;
}

int Serveur::envoyerSon(){
    return 0;
}

int Serveur::recevoirSon(){
    return 0;
}

bool Serveur::gestionSon(){
    bool rester = true;
    FD_ZERO(&rfds);
    FD_SET(sockSon, &rfds);
    tv.tv_sec = 0;
    tv.tv_usec = 0;
    retval = select(sockSon+1, &rfds, NULL, NULL, &tv);
    if(retval==-1){
        rester = false;
    }
    if(sonDisponible()){
        envoyerSon();
    }

    if(FD_ISSET(sockSon,&rfds)){
        recevoirSon();
    }

    return rester;
}



int Serveur::chat(){

    bool resterTexte = true;
    bool resterSon = true;

    while(resterTexte && resterSon){
        resterTexte = gestionTexte();

        if(moduleSon){
            resterSon = gestionSon();
        }
    }
    return retval;
}
